﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.Utility._MD5;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyBlog.JWT.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthoizeController : ControllerBase
    {
        private readonly IWriteInfoService _writeInfoService;
        public AuthoizeController(IWriteInfoService writeInfoService)
        {
            this._writeInfoService = writeInfoService;
        }

        [HttpPost("Login")]
        public async Task<ApiResult> Login(string username, string userpwd)
        {
            try
            {
                //密码加密
                string pwd = MD5Helper.MD5Encrypt32(userpwd);
                //数据校验
                var write = await _writeInfoService.FindAsync(c => c.UserName == username && c.UserPwd == pwd);
                if (write == null) return ApiResultHelper.Error("账户或密码错误");

                //JWT授权
                var clamis = new Claim[] {
                new Claim(ClaimTypes.Name,write.Name),
                new Claim("Id",write.Id.ToString()),
                new Claim("UserName",write.UserName)
                //注意：这里不能放敏感信息，如密码
                };
                //通过 this.User.Identity.Name //访问到clamis的内容   Identity 是身份的意思


                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));//注意：这秘钥字符串要跟鉴权的一致才行！
                var token = new JwtSecurityToken(
                      issuer: "http://localhost:6060", //颁发Token的Web应用程序
                      audience: "http://localhost:5000", //Token的受理者
                      claims: clamis,
                      notBefore: DateTime.Now,
                      expires: DateTime.Now.AddHours(1),//过期时间
                      signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)

                    );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);//生成token值


                return ApiResultHelper.Success(jwtToken);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
    }
}
